import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Input, message, } from 'antd';
import { Image, Button, ImageViewer, Mask, Picker, } from 'antd-mobile'
import styles from './index.module.css'
import { LocationFill, CameraOutline, UnorderedListOutline } from 'antd-mobile-icons'

import { getWxOpenId, getSession, getWxJsConfig, getAddress, submitCase } from '../../utils/axiosRequest/api'
import { setCache, removeAllCache } from '../../utils/cache/'
import { session_cache_key } from '../../utils/cache/cacheKey'
//加解密
import { encryptMD5 } from "../../utils/crypt/index"

import { jumpTo } from '../../utils/jump'


function CaseReport() {
    //微信JSSDK
    const wx = React.useRef();
    //导航
    const navigate = useNavigate()
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    const { TextArea } = Input;
    //微信昵称
    const [wxName, setWxName] = useState('');
    //当前位置-详细信息
    const [loaction, setLoaction] = useState('');
    //当前位置-详细信息
    const [loactionState, setLoactionState] = useState('定位中...');
    //当前位置
    const [resLocation, setResLocation] = useState();
    //预览图片的状态
    const [imagVisible, setImagVisible] = useState(false)
    //确认提交案件弹框状态
    const [isOrderModalOpen, setIsOrderModalOpen] = useState(false);
    //案件确认提交加载状态
    const [isConfirmState, setIsConfirmState] = useState(false);
    //本地图片信息
    const [localIds, setLocalIds] = useState([]);
    //上传微信服务器成功后的图片id
    const [serverIds, setServerIds] = useState([]);
    //图片预览
    const [previewImgUrl, setPreviewImgUrl] = useState();
    //案件选择框状态
    const [pickerCaseVisible, setPickerCaseVisible] = useState(false)
    //案件内容
    const [pickerCaseValue, setPickerCaseValue] = useState()
    //案件选择框加载状态
    const [isCasePicekLoad, setIsCasePicekLoad] = useState(false)


    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        return () => {
        }
    }, []);

    function initData() {
        //初始化微信js
        wx.current = window.wx;
        getSessionInfo()

    }

    function getSessionInfo() {
        const timestamp = Date.now().toString();
        const issue = "hm";
        const version = "V100";
        const channel = "web";
        const author = "PCS";
        const permission = "10117aaa";
        //签名按照顺序channel->version->author->permission->issue全小写再md5
        const signature = timestamp.toLowerCase() + channel.toLowerCase() + version.toLowerCase() + author.toLowerCase() + permission.toLowerCase() + issue.toLowerCase()
        //构建请求参数
        const params = new Map()
        params.set('timestamp', timestamp)
        params.set('issue', issue)
        params.set('version', version)
        params.set('channel', channel)
        params.set('author', author)
        params.set('permission', permission)
        params.set('signature', encryptMD5(signature))
        getSession(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //先删除所有缓存
                    removeAllCache()
                    //保存session
                    setCache(session_cache_key, data.data.sessionId);
                    //获取微信公众号唯一标识
                    getWXCode();
                    //获取js配置
                    initWxJsConfig()
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    function getWXCode() {
        //当前url,要拿到code换取微信唯一标识
        //处理url->当前网页的URL，不包含#及其后面部分
        const url = window.location.href.split('#')[0]
        //获取用户唯一标识,先获取url中的code
        const urlObj = new URL(url);
        //使用URLSearchParams获取所有参数
        const paramsList = new URLSearchParams(urlObj.search);
        //使用forEach遍历所有参数
        const allParams = {};
        paramsList.forEach((value, key) => {
            allParams[key] = value;
        });
        //1、拿到code
        const code = allParams.code;
        //2、通过code换取access_token->最后得到唯一标识openid
        const params = new Map()
        params.set('code', code)
        getWxOpenId(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    setWxName(data.data.openid);
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }


    function initWxJsConfig() {
        //处理url->当前网页的URL，不包含#及其后面部分
        const url = window.location.href.split('#')[0]
        const params = new Map()
        params.set('hrefUrl', url)
        getWxJsConfig(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    wxConfig(data.data)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }


    //注册微信公众号js
    function wxConfig(data) {
        wx.current.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名
            jsApiList: ['openLocation', 'getLocation', 'chooseImage', 'uploadImage', 'hideAllNonBaseMenuItem'] // 必填，需要使用的JS接口列表
        });

        wx.current.ready(function () {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
            //所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。

            //隐藏所有非基础按钮接口
            wx.current.hideAllNonBaseMenuItem()

            //获取地理位置
            wx.current.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    let speed = res.speed; // 速度，以米/每秒计
                    let accuracy = res.accuracy; // 位置精度
                    setResLocation(res);
                    initAddress(res);
                    setLoactionState('位置')
                },
                fail: function (res) {
                    messageApi.open({ type: 'error', content: res.errMsg });
                    setLoactionState('定位失败')
                }
            });

        });
    }

    function initAddress(res) {
        //逆地理编码
        const params = new Map()
        params.set('latitude', res.latitude)
        params.set('longitude', res.longitude)
        getAddress(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    setLoaction(data.data.standardAddress)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //打开相机
    function openCamera() {
        const picSize = localIds.length
        if (picSize > 2) {
            messageApi.open({ type: 'error', content: '最多只能上传3张照片' });
            return
        }
        wx.current.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                const locaId = localIds[0]; //localIds是个数组
                uploadPic(locaId)
            }
        });
    }


    function uploadPic(locaId) {
        wx.current.uploadImage({
            localId: locaId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                addImage(locaId)//展示图片
                //serverId是字符串
                let serverId = res.serverId; // 返回图片的服务器端ID
                addServerId(serverId)//添加服务id

            },
            fail: function (res) {
                messageApi.open({ type: 'error', content: '上传失败：' + res.errMsg });
            }
        })
    }

    //打开地图
    function openMap() {
        if (loaction === '') {
            messageApi.open({ type: 'error', content: '定位中请稍后...' });
            return
        }
        wx.current.openLocation({
            latitude: resLocation.latitude, // 纬度，浮点数，范围为90 ~ -90
            longitude: resLocation.longitude, // 经度，浮点数，范围为180 ~ -180。
            name: loaction, // 位置名
            address: '', // 地址详情说明
            scale: 17, // 地图缩放级别,整型值,范围从1~28。默认为最大
            infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
        });
    };

    //预览图片
    function previewImg(index) {
        setImagVisible(true)
        setPreviewImgUrl(localIds[index])
    }

    //增加图片
    function addImage(locaId) {
        setLocalIds([...localIds, locaId]);
    };

    //增加服务器图片服务器id
    function addServerId(serverId) {
        setServerIds([...serverIds, serverId])
    }


    //点击提交
    function submitOrder() {
        setIsOrderModalOpen(true);
    }

    //确认提交
    function confirmOrder() {
        setIsConfirmState(true)
        jumpTo(navigate, '/reportResults', true, { caseNumber: '2017182818828182881' })
        //开始提交
        // const params = new Map()
        // params.set('serverId', serverIds)
        // submitCase(params)
        //     .then(response => {
        //         const data = response.data
        //         if (data.code === '000') {
        //             //提交成功->跳转成功页面
        //             jumpTo(navigate, '/reportResults', true, null)
        //         } else {
        //             //处理失败
        //             messageApi.open({ type: 'error', content: data.des });
        //         }
        //         setIsConfirmState(false)
        //     })
        //     .catch(error => {
        //         messageApi.open({ type: 'error', content: error.message });
        //         setIsConfirmState(false)
        //     });
    }

    //确认取消
    function cancleOrder() {
        if (isConfirmState) {
            //加载状态不能取消
            messageApi.open({ type: 'error', content: '正在提交中！' });
            return
        }
        setIsOrderModalOpen(false)
    }

    //确认框取消
    function afterClose() {
        //重置加载状态
        setIsConfirmState(false)
    }

    const basicColumns = [
        [
            { label: '1、暴露垃圾', value: '暴露垃圾111' },
            { label: '2、暴露垃圾', value: '暴露垃圾222' },
            { label: '3、暴露垃圾', value: '暴露垃圾333' },
            { label: '4、暴露垃圾', value: '暴露垃圾444' },
            { label: '5、暴露垃圾', value: '暴露垃圾555' },
        ],

    ]

    //案件类型选择
    function pickCase() {
        setPickerCaseVisible(true)
    }

    return (
        <div className={styles.root}>
            {contextHolder}
            <span>微信ID：{wxName}</span>
            <div className={styles.contact_person_box}>
                <span>联系人名称：</span> <Input maxLength={5} type={'text'} className={styles.inp_name} defaultValue={''} placeholder="请输入联系人名称..." variant="outlined" />
            </div>
            <div className={styles.contact_phone_box}>
                <span>联系方式：</span> <Input type={'number'} maxLength={11} className={styles.inp_phone} defaultValue={''} placeholder="请输入联系方式..." variant="outlined" />
            </div>
            <div className={styles.case_location_box}>
                <div className={styles.case_location_item}>
                    <span className={styles.case_location_title} >案件类型：</span>
                    <Button onClick={pickCase} color='primary' size='small'><UnorderedListOutline /> 选择</Button>
                </div>
                <span className={styles.case_location_des}>{pickerCaseValue}</span>
                <Picker
                    loading={isCasePicekLoad}
                    confirmText={'选择'}
                    columns={basicColumns}
                    visible={pickerCaseVisible}
                    onClose={() => {
                        setPickerCaseVisible(false)
                    }}
                    value={pickerCaseValue}
                    onConfirm={v => {
                        setPickerCaseValue(v)
                    }}
                />
            </div>
            <div className={styles.case_location_box}>
                <div className={styles.case_location_item}>
                    <span className={styles.case_location_title} >案件位置：</span>
                    <Button onClick={openMap} color='primary' size='small'><LocationFill /> {loactionState}</Button>
                </div>
                <span className={styles.case_location_des}>{loaction}</span>
            </div>
            <div className={styles.case_location_box}>
                <span>详细描述：</span>
                <TextArea className={styles.case_problem_des} rows={4} placeholder="最多输入50个字符..." maxLength={50} />
            </div>
            <div className={styles.case_img_box}>
                <div className={styles.case_location_item}>
                    <span className={styles.case_location_title} >案件图片：</span>
                    <Button onClick={openCamera} color='primary' size='small'> <CameraOutline /> 拍照</Button>
                </div>
                <div className={styles.img_box}>
                    {
                        localIds.map((image, index) => (
                            <div className={styles.img_item}>
                                <Image onClick={() => { previewImg(index) }} width={110} height={110} fit='fill' key={index} src={image} />
                            </div>
                        ))
                    }
                </div>
                <ImageViewer
                    image={previewImgUrl}
                    visible={imagVisible}
                    onClose={() => { setImagVisible(false) }} />
            </div>
            <Mask visible={isOrderModalOpen} afterClose={afterClose}>
                <div className={styles.config_dialog_box} >
                    <div className={styles.config_dialog}>
                        <span className={styles.config_title}>是否确认提交？</span>
                        <Button loading={isConfirmState} onClick={confirmOrder} className={styles.config_btnOk} block color='primary' size='large' loadingText='正在提交'>确认</Button>
                        <Button onClick={cancleOrder} className={styles.config_btnCancel} block fill='outline' color='primary' size='large'>取消</Button>
                    </div>
                </div>
            </Mask>
            <Button className={styles.case_submit_btn} onClick={submitOrder} block color='primary' size='large'>提交</Button>
        </div>
    )
}

export default CaseReport;
